package com.examstack.management.controller.action;

import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.examstack.common.domain.exam.*;
import com.examstack.common.domain.question.CheckRecord;
import com.examstack.common.domain.question.Question;
import com.examstack.common.util.file.ExportExcelUtil;
import com.examstack.management.security.UserInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.examstack.management.service.ExamPaperService;
import com.examstack.management.service.ExamService;
import com.google.gson.Gson;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class ExamAction {
	@Autowired
	private ExamPaperService examPaperService;
	@Autowired
	private ExamService examService;
	@RequestMapping(value = "/api/exampaper/{id}", method = RequestMethod.GET)
	public @ResponseBody ExamPaper getExamPaper(@PathVariable("id") int id){
		ExamPaper paper = examPaperService.getExamPaperById(id);
		return paper;
	}
	
	@RequestMapping(value = "/api/answersheet", method = RequestMethod.POST)
	public @ResponseBody Message submitAnswerSheet(@RequestBody AnswerSheet answerSheet){

		List<AnswerSheetItem> itemList = answerSheet.getAnswerSheetItems();
		
		//全部是客观题，则状态更改为已阅卷
		int approved = 3;
		for(AnswerSheetItem item : itemList){
			if(item.getQuestionTypeId() != 1 && item.getQuestionTypeId() != 2 && item.getQuestionTypeId() != 3){
				approved = 2;
				break;
			}
		}
		Gson gson = new Gson();		
		examService.updateUserExamHist(answerSheet, gson.toJson(answerSheet),approved);
		
		return new Message();
	}

	@RequestMapping(value = "/common/exam/check-exampaper/{exampaperId}", method = RequestMethod.GET)
	public @ResponseBody Message checkExamPaper(Model model, @PathVariable("exampaperId") int exampaperId) {

		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Message message = new Message();
		try {
			List<Exam> list=examService.getExamByPaperId(exampaperId);
			if(list.size()>0){
				message.setResult("failure");
			}
		} catch (Exception ex) {
			message.setResult(ex.getClass().getName());
		}

		return message;
	}

	@RequestMapping(value = "/common/exam/check-examhistory/{exampaperId}", method = RequestMethod.GET)
	public @ResponseBody Message checkExamPaperHistory(Model model, @PathVariable("exampaperId") int exampaperId) {

		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Message message = new Message();
		try {
			List<ExamHistory> list=examService.getUserExamHistListByExamPaperId(exampaperId);
			if(list.size()>0){
				message.setResult("failure");
			}
		} catch (Exception ex) {
			message.setResult(ex.getClass().getName());
		}

		return message;
	}

	@RequestMapping(value = "/common/excel/export-{examId}")
	public void exportExcel(HttpServletRequest request, HttpServletResponse response, @PathVariable int examId) throws UnsupportedEncodingException {
		List<ExamHistory> histList = examService.getUserExamHistListByExamId(examId, null, null, 0, null);
		SimpleDateFormat sdf = new SimpleDateFormat("HHmm");
		ExportExcelUtil<ExamHistory> util = new ExportExcelUtil<ExamHistory>();
		String userAgent = request.getHeader("USER-AGENT");
		String fileName= sdf.format(new Date())+"_"+histList.get(0).getExamName()+"成绩.xls";
		String finalFileName = null;
		if(userAgent.contains("MSIE")){//IE浏览器
			finalFileName = URLEncoder.encode(fileName,"UTF8");
		}else if(userAgent.contains("Mozilla")){//google,火狐浏览器
			finalFileName = new String(fileName.getBytes(), "ISO8859-1");
		}else{
			finalFileName = URLEncoder.encode(fileName,"UTF8");//其他浏览器
		}
		String[] columnNames = {"准考证号","用户名","姓名","开始时间","总分","及格分","得分","是否通过","交卷时间","考试状态","部门"};
		for(ExamHistory examHistory:histList){
			if(examHistory.getPointGet()>=examHistory.getPassPoint()){
				examHistory.setContent("已通过");
			}else{
				examHistory.setContent("未通过");
			}
			if(examHistory.getAnswerSheet()==null){
				examHistory.setNationalId("未考试");
			}else{
				examHistory.setNationalId("已阅卷");
			}
		}
		HSSFWorkbook hssfWorkbook=util.exportExcel2003(histList.get(0).getExamName()+"成绩", columnNames, histList, "yyyy-MM-dd HH:mm:ss");
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-Disposition", "attachment; filename=\"" + finalFileName + "\"");//这里设置一下让浏览器弹出下载提示框，而不是直接在浏览器中打开
		try {
			OutputStream ouputStream = response.getOutputStream();
			hssfWorkbook.write(ouputStream);
			ouputStream.flush();
			ouputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
